﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;


namespace Tsingda.CacheModule
{
    public class CacheManage
    {
        private static readonly int cacheMinutes = 1;
        internal static ICache cache = new StaticCache();

        /// <summary>
        /// 向缓存中添加内容
        /// </summary>
        /// <param name="key"></param>
        /// <param name="memo"></param>
        public static void Add(string key, object memo)
        {
            cache.Add(CreateKey(key), memo, cacheMinutes);
        }

        /// <summary>
        /// 缓存对象中是否存在key的缓存项,True 存在;False 不存在
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool Container(string key)
        {
            return cache.Container(CreateKey(key));
        }

        /// <summary>
        /// 移除指定的缓存项
        /// </summary>
        /// <param name="key"></param>
        public static void Remove(string key)
        {
            cache.Remove(CreateKey(key));
        }

        /// <summary>
        /// 获取指定的缓存项
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string Get(string key)
        {
            return cache.Get(CreateKey(key)).ToString();
        }

        /// <summary>
        /// 输出缓存内容信息
        /// </summary>
        /// <param name="application"></param>
        /// <param name="key"></param>
        public static void Write(System.Web.HttpApplication application, string key)
        {
            cache.Write(application, CreateKey(key));
        }


        /// <summary>
        /// 对URL路径做MD5编码,作为缓存的 Key
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string CreateKey(string key)
        {
            return EncryptString(key.Trim());
        }

        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static string EncryptString(string str)
        {
            byte[] buffer = System.Security.Cryptography.MD5.Create().ComputeHash(System.Text.Encoding.UTF8.GetBytes(str));
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < buffer.Length; i++)
            {
                builder.Append(buffer[i].ToString("X2"));
            }
            return builder.ToString();
        }
    }
}
